package web.comment;

import entity.UserEntity;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(urlPatterns = {"/dao/register"})
public class register extends HttpServlet {
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        String name = request.getParameter("username");
        String youxiang = request.getParameter("usertel");
        String tel = request.getParameter("password");
        String vip = request.getParameter("usertype");
        UserEntity userEntity = new UserEntity();
        userEntity.setVip(vip);
        userEntity.setPhone(tel);
        userEntity.setEmail(youxiang);
        userEntity.setName(name);

        EntityManager em = (EntityManager) request.getAttribute("_entity.Manager");
        Query query = em.createNativeQuery("select uid from UserEntity where name = ?");
        query.setParameter(1, name);
        List list = query.getResultList();
        if(list.size()==1){
            request.getSession().setAttribute("error", "该账号已存在！！");
            response.sendRedirect("http://localhost:8080/user/login.jsp");
        } else {
            em.persist(userEntity);
            request.getSession().setAttribute("error", "注册成功！！");
            response.sendRedirect("http://localhost:8080/user/login.jsp");
        }
    }
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
        doGet(request,response);
    }
}
